<template>
  <el-form v-loading="loading" label-position="right" label-width="100px" ref="form" :rules="rules" :model="form">
    <el-row>
      <el-col :span="24">
        <el-form-item label="疾病名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入疾病名称"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" type="number" placeholder="请输入排序"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-form-item class="contacts-add">
      <el-button type="primary" @click="onSubmit">提交</el-button>
      <el-button @click="cancle">关闭</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import * as APIMedicalCare from '@/api/medicalCare';
import { mapState } from 'vuex'
 import { unixToDate } from "@/utils";
export default {
  name: 'medicine-add',
  props: {
    data: {
      type: Object,
      default: () => {}
    }
  },
  computed: {
    ...mapState('d2admin/user', [
      'info'
    ])
  },
  data () {
    return {
      form: {},
      loading: false,
      // 表单校验
      rules: {
        name: [
          { required: true,  message: '请输入疾病名称', trigger: 'blur'  }
        ],
        sort: [
          { required: true, message: '请输入排序',trigger: 'blur' }
        ],
      }
    }
  },
  mounted () {
  },
  methods: {
    getIllnessInfo(id){
      const self = this;
      this.loading = true;
      APIMedicalCare.illnessInfo({id: id}).then((resp) => {
        const res = resp.data;
        self.form = Object.assign({},{ id: res.id, name: res.name, sort: res.sort});
      }).finally(() => {
        this.loading = false
      });
    },
    onSubmit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.form.id) {
            APIMedicalCare.illnessEdit(this.form).then(res => {
              this.$message({ type: "success", message: "编辑成功!"});
              this.cancle()
              this.load()
            })
          } else {
            APIMedicalCare.illnessAdd(this.form).then(res => {
              this.$message({ type: "success", message: "新增成功!"});
              this.cancle()
              this.load()
            })
          }
        }
      })
    },
    load () {
      this.$emit('load')
    },
    cancle () {
      this.$refs.form.resetFields()
      this.$emit('cancle')
    }
  },
  watch: {
    data: {
      handler (newval) {
        if(newval.hasOwnProperty('id')){
          this.getIllnessInfo(newval['id']);
        } else {
           this.form = { ...newval };
        }
      },
      // 可以一进页面就触发监听器  监听器自带的immediate
      immediate: true,
      deep: true
    }
  }
}
</script>

<style lang="scss">
.contacts-add {
  text-align: right;
}
.contract-text {
  font-size: 12px;
  color: #999;
  line-height: 12px;
  margin: 0;
}
.contract-img {
  width: 146px;
  height: 146px;
  cursor: pointer;
}
</style>
